﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace syc.Store
{
    public partial class 产品出库单录入 : System.Web.UI.Page
    {
        protected string Notice = "";
        private string kidlist = "";
        private int ks = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            int BillID = 0;
            int htid = 0;

            if (!this.IsPostBack)
            {
                if ((object)Session["OperatorDCode"] != null)
                {
                    string dcode = (string)Session["OperatorDCode"];
                    if (dcode != "3505")
                    {
                        this.Button_Pass.Enabled = false;
                    }
                }

                if (Request.QueryString["ID"] != null)
                {
                    int.TryParse(Request.QueryString["ID"], out BillID);
                }
                if (Request.QueryString["HTID"] != null)
                {
                    int.TryParse(Request.QueryString["HTID"], out htid);
                }
                if (BillID > 0)
                {
                    LoadBill(BillID);
                }
                else if (htid > 0)//录入新入库单
                {
                    this.Date1.Text = DateTime.Today.ToLongDateString();
                    this.KuGuanYuan.Text = (string)Session["OperatorName"];
                    LoadHT(htid);
                 }
                else
                {
                    Response.Redirect("选择销售合同.aspx");
                }
            }
        }
        private void LoadHT(int htid)
        {
            SqlConnection Conn = new SqlConnection();
            Conn.ConnectionString = ConfigurationManager.ConnectionStrings["SCMConnectionString1"].ConnectionString;
            Conn.Open();
            SqlCommand Cmd = new SqlCommand();
            Cmd.Connection = Conn;
            Cmd.CommandText =
@"select t2.名称 as 订货单位,
t1.合同编号,
t1.产品ID as 产品ID,
t1.订货单位ID,
t3.品名,
t3.规格,
t1.运输方式
from 产品销售合同 t1
left outer join 产品订货单位 t2 on t2.ID=t1.订货单位ID
left outer join 产品 t3 on t3.ID=t1.产品ID
where t1.ID=" + htid;
            Cmd.CommandType = CommandType.Text;
            SqlDataReader Reader = Cmd.ExecuteReader();
            if (Reader.Read())
            {
                this.DingHuo.Text = (string)Reader["订货单位"];
                this.HeTongHao.Text = ((string)Reader["合同编号"]).Trim();
                this.ChanPin.Text = (string)Reader["品名"];
                this.GuiGe.Text = (string)Reader["规格"];
                this.FaHuoFangShi.Text = ((string)Reader["运输方式"]).Trim();
                this.HeTongID.Text = htid.ToString();
                this.ChanPinID.Text = ((int)Reader["产品ID"]).ToString();
                if (this.ChanPinID.Text == "3" || this.ChanPinID.Text == "4")
                {
                    this.GangJi.Text = "N80Q";
                }
                else
                {
                    this.GangJi.Text = "J55";
                }
                this.DHID.Text = ((int)Reader["订货单位ID"]).ToString();
            }
            else
            {
                this.Notice = "·合同号不存在";
                this.Button_Save.Visible = false;
            }
            Reader.Close();
            Conn.Close();
            Reader.Dispose();
            Cmd.Dispose();
            Conn.Dispose();

        }
        private void LoadBill(int BillID)
        {

            SqlConnection Conn = new SqlConnection();
            Conn.ConnectionString = ConfigurationManager.ConnectionStrings["SCMConnectionString1"].ConnectionString;
            Conn.Open();
            SqlCommand Cmd = new SqlCommand();
            Cmd.Connection = Conn;
            Cmd.CommandText =
@"select t1.合同ID,t1.产品类别ID as 产品ID,t1.日期,t2.订货单位,t2.订货单位ID,t2.合同编号,t1.序号,t2.品名,t2.规格,t1.生产线,
t1.总件数,t1.总支数,t1.总重量,t1.总长度,t2.运输方式,t1.备注,t1.车号,t1.仓储主管,t1.库管员,t1.是否合格,t1.是否送检
from 产品出库单 t1 left outer join 产品销售合同视图 t2 on t1.合同ID=t2.ID where t1.ID=" + BillID;
            Cmd.CommandType = CommandType.Text;
            SqlDataReader Reader = Cmd.ExecuteReader();
            if (Reader.Read())
            {
                this.ShengChan.Enabled = false;
                this.BillID.Text = BillID.ToString();
                this.HeTongID.Text = ((int)Reader["合同ID"]).ToString();
                this.ChanPinID.Text = ((int)Reader["产品ID"]).ToString();
                this.DHID.Text = ((int)Reader["订货单位ID"]).ToString();

                this.Date1.Text = ((DateTime)Reader["日期"]).ToLongDateString();
                this.DingHuo.Text = (string)Reader["订货单位"];
                this.HeTongHao.Text = ((string)Reader["合同编号"]).Trim();
                this.XuHao.Text = ((int)Reader["序号"]).ToString();
                this.ChanPin.Text = (string)Reader["品名"];
                this.GuiGe.Text = (string)Reader["规格"];
                if (this.ChanPinID.Text == "3" || this.ChanPinID.Text == "4")
                {
                    this.GangJi.Text = "N80Q";
                }
                else
                {
                    this.GangJi.Text = "J55";
                }
                this.ShengChan.Text = ((short)Reader["生产线"]).ToString();

                this.ZJS.Text = ((byte)Reader["总件数"]).ToString();
                this.ZZS.Text = ((short)Reader["总支数"]).ToString();
                this.ZZL.Text = ((decimal)Reader["总重量"]).ToString();
                this.ZCD.Text = ((decimal)Reader["总长度"]).ToString();

                this.FaHuoFangShi.Text = (string)Reader["运输方式"];
                this.BeiZhu.Value = (string)Reader["备注"];
                this.CheHao.Value = ((string)Reader["车号"]).Trim();
                this.KuGuanYuan.Text = ((string)Reader["库管员"]).Trim();

                if ((bool)Reader["是否合格"])
                {
                    this.Button_Pass.Text = "取消盖章";
                    this.PDZ.Visible = true;
                    this.Date1.Enabled = false;
                    this.XuHao.Enabled = false;
                    this.ReadOnly.Text = "true";
                    this.Button_Save.Visible = false;
                }
                else
                {
                    this.Button_Deliver.Visible = true;
                }
                if ((bool)Reader["是否送检"])
                {
                    this.Button_Deliver.Text = "取消送检";
                    this.Button_Pass.Visible = true;
                    this.Date1.Enabled = false;
                    this.XuHao.Enabled = false;
                    this.ReadOnly.Text = "true";
                    this.Button_Save.Visible = false;
                    this.Button_Verify.Visible = false;
                }
                else
                {
                    this.Button_Deliver.Text = "送 检";
                    this.Button_Pass.Visible = false;
                }

                Reader.Close();
                Cmd.CommandText =
@"select t1.ID as 库存ID,t1.原料供货ID,t2.名称 as 供货,t1.炉号,t1.捆号,t1.重量,t1.长度
from 产品库存 t1 left outer join 原料供货单位 t2 on t1.原料供货ID=t2.ID where t1.状态=2
and t1.产品类别ID=" + this.ChanPinID.Text + " and t1.生产线=" + this.ShengChan.Text + " and t1.出库单ID=" + BillID;

                Reader = Cmd.ExecuteReader();
                string kh;
                while (Reader.Read())
                {
                    this.GHList.Value += "|" + (string)Reader["供货"];
                    this.LHList.Value += "|" + (string)Reader["炉号"];

                    kh = ((int)Reader["捆号"]).ToString();
                    if (kh.Length < 9)
                    {
                        kh = new string('0', 9-kh.Length) + kh;
                    }
                    kh = kh.Substring(0, 4) + "-" + kh.Substring(5);

                    this.KHList.Value += "|" + kh;
                    this.ZLList.Value += "|" + (decimal)Reader["重量"];
                    this.CDList.Value += "|" + (decimal)Reader["长度"];
                }   
            }
            else
            {
                this.Notice = "·出库单不存在";
                this.Button_Save.Visible = false;
            }
            Reader.Close();
            Conn.Close();
            Reader.Dispose();
            Cmd.Dispose();
            Conn.Dispose();
        }

        protected void Button_Save_Click(object sender, EventArgs e)
        {

            string bz = Verify();
            if (this.BeiZhu.Value == "")
            {
                this.BeiZhu.Value = bz;
            }


            if (this.Notice != "·数据校验通过")
            {
                this.Notice += " ·保存失败";
                return;
            }
            int xh;
            DateTime d;
            if (!int.TryParse(this.XuHao.Text, out xh))
            {
                this.Notice = "“序号”录入有误，需录入一个正整数";
                return;
            }
            else if (!DateTime.TryParse(this.Date1.Text, out d))
            {
                this.Notice = "“日期”录入有误";
                return;
            }

            SqlConnection Conn = new SqlConnection();
            Conn.ConnectionString = ConfigurationManager.ConnectionStrings["SCMConnectionString1"].ConnectionString;
            Conn.Open();
            SqlTransaction Tran = Conn.BeginTransaction();
            SqlCommand Cmd = new SqlCommand();
            Cmd.Connection = Conn;
            Cmd.Transaction = Tran;
            try
            {
                if (this.BillID.Text != "0")
                {
                    Cmd.CommandText = "set nocount on;update 产品出库单 set 序号=" + xh
                        + ",生产线=" + this.ShengChan.Text
                        + ",日期='" + d.ToShortDateString()
                        + "',总件数=" + this.ZJS.Text
                        + ",总支数=" + this.ZZS.Text
                        + ",总重量=" + this.ZZL.Text
                        + ",总长度=" + this.ZCD.Text
                        + ",备注=cast('" + this.BeiZhu.Value.Replace("'", "''") + "' as nvarchar(100))"
                        + ",车号=cast('" + this.CheHao.Value.Replace("'", "''") + "' as char(15)) where ID="
                        + this.BillID.Text + ";";
                    Cmd.CommandText = Cmd.CommandText + "update 产品库存 set 出库单ID=0,状态=1,出库日期=null where 出库单ID=" + this.BillID.Text + ";";
                    Cmd.CommandText = Cmd.CommandText + "set nocount off;update 产品库存 set 出库单ID=" + this.BillID.Text + ",状态=2,出库日期='"
                        + d.ToShortDateString() + "' where 状态=1 and ID in(" + kidlist + ")";
                    if (ks != Cmd.ExecuteNonQuery())
                    {
                        throw new Exception("·保存失败");
                    }
                }
                else
                {
                    string op = (string)this.Session["OperatorName"];
                    if (op == null)
                    {
                        op = "";
                    }
                    Cmd.Parameters.Add(new SqlParameter("@ID", SqlDbType.Int, 4, ParameterDirection.Output, true, 0, 0, "", DataRowVersion.Proposed, null));
                    Cmd.CommandText = "set nocount on;insert into 产品出库单(序号,合同ID,产品类别ID,生产线,订货单位ID,日期,总件数,总支数,总重量,总长度,库管员,备注,车号)values("
                        + xh
                        + "," + this.HeTongID.Text
                        + "," + this.ChanPinID.Text
                        + "," + this.ShengChan.Text
                        + "," + this.DHID.Text
                        + ",'" + d.ToShortDateString() + "'"
                        + "," + this.ZJS.Text
                        + "," + this.ZZS.Text
                        + "," + this.ZZL.Text
                        + "," + this.ZCD.Text
                        + ",'" + op + "'"
                        + ",cast('" + this.BeiZhu.Value.Replace("'", "''") + "' as nvarchar(100))"
                        + ",cast('" + this.CheHao.Value.Replace("'", "''") + "' as char(15)) );set @ID=@@IDENTITY;";
                    
                    Cmd.CommandText = Cmd.CommandText + "set nocount off;update 产品库存 set 出库单ID=@ID,状态=2,出库日期='"
                                            + d.ToShortDateString() + "' where 状态=1 and ID in(" + kidlist + ")";
                    if (ks != Cmd.ExecuteNonQuery())
                    {
                        throw new Exception("·保存失败");
                    }
                    this.BillID.Text = ((int)Cmd.Parameters["@ID"].Value).ToString();
                }

                Tran.Commit();
                this.ShengChan.Enabled = false;
                this.Button_Deliver.Visible = true;
                this.Notice = "·保存成功";
            }
            catch (Exception err)
            {
                Tran.Rollback();
                this.Notice = err.Message;
            }

            Cmd.Dispose();
            Tran.Dispose();
            Conn.Close();
            Conn.Dispose();

        }

        protected void Button_Deliver_Click(object sender, EventArgs e)
        {
            string[] ds = new string[] { "取消送检", "送 检" };
            int po=0;
            if (this.Button_Deliver.Text == ds[1])
            {
                po = 1;
            }
            this.SqlDataSource1.UpdateCommand = "update 产品出库单 set 是否送检=" + po
                + " where ID=" + this.BillID.Text;
            if (this.SqlDataSource1.Update() > 0)
            {
                this.Button_Deliver.Text = ds[(po + 1) % 2];
                if (po == 1)
                {
                    this.ReadOnly.Text = "true";
                    this.Button_Pass.Visible = true;
                    this.Date1.Enabled = false;
                    this.XuHao.Enabled = false; 
                    this.Button_Save.Visible = false;
                    this.Button_Verify.Visible = false;
                }
                else
                {
                    this.ReadOnly.Text = "false";
                    this.Button_Pass.Visible = false;
                    this.Date1.Enabled = true;
                    this.XuHao.Enabled = true; 
                    this.Button_Save.Visible = true;
                    this.Button_Verify.Visible = true;
                }
            }
        }

        protected void Button_Pass_Click(object sender, EventArgs e)
        {

            string[] ds = new string[] { "取消盖章", "盖 章" };
            int po = 0;
            if (this.Button_Pass.Text == ds[1])
            {
                po = 1;
            }
            this.SqlDataSource1.UpdateCommand = "update 产品出库单 set 是否合格=" + po
                + " where ID=" + this.BillID.Text;
            if (this.SqlDataSource1.Update() > 0)
            {
                this.Button_Pass.Text = ds[(po + 1) % 2];
                if (po == 1)
                {
                    this.PDZ.Visible = true;
                    this.Button_Deliver.Visible = false;
                }
                else
                {
                    this.PDZ.Visible = false;
                    this.Button_Deliver.Visible = true;
                }
            }
        }

        protected void Button_Verify_Click(object sender, EventArgs e)
        {
            this.BeiZhu.Value+=Verify();
        }

        protected string Verify()
        {
            int i,t;
 
            if (KHList.Value=="")
            {
                this.Notice = "·您没有录入任何捆号";
                return "";
            }
            
            int[] khs = new int[28];
            string kunhaodlist = KHList.Value.Substring(1).Replace("-", "0").Replace("|",",");
            string[] tmp = kunhaodlist.Split(new Char[] { ',' });
            ks = tmp.Length;
            string[] ghs = new string[ks];
            string[] lhs = new string[ks];
            string[] zls = new string[ks];
            string[] cds = new string[ks];
            int zzs = 0;
            int zjs = 0;
            byte zs = 0;
            string beizhu = "";
            decimal zzl = 0;
            decimal zcd = 0;
            for (i = 0; i < ks && i < 28; i++)
            {
                ghs[i] = "";
                lhs[i] = "";
                zls[i] = "";
                cds[i] = "";

                if (int.TryParse(tmp[i], out t))
                {
                    khs[i] = t;
                }
                else
                {
                    Response.End();
                    return "";
                }
            }

            SqlConnection Conn = new SqlConnection();
            Conn.ConnectionString = ConfigurationManager.ConnectionStrings["SCMConnectionString1"].ConnectionString;
            Conn.Open();
            SqlCommand Cmd = new SqlCommand();
            Cmd.Connection = Conn;
            string sql = "select t1.ID,t2.名称 as 原料供货,t1.炉号,t1.捆号,t1.重量,t1.长度,t1.支数"
            + " from 产品库存 t1 left outer join 原料供货单位 t2 on t2.ID=t1.原料供货ID where ";
            if (this.BillID.Text == "0")
            {
                sql += "t1.状态=1";
            }
            else
            {
                sql += "(t1.状态=1 or t1.出库单ID="+ this.BillID.Text + ")";
            }
            sql += " and t1.产品类别ID=" + this.ChanPinID.Text + " and t1.生产线="
            + this.ShengChan.Text + " and t1.捆号 in(" + kunhaodlist + ")";

            Cmd.CommandText = sql;

            //Response.Write(Cmd.CommandText);

            SqlDataReader Reader = Cmd.ExecuteReader();
            string ts;
            while (Reader.Read())
            {
                kidlist += "," + (int)Reader["ID"];
                zs=(byte)Reader["支数"];
                zzs += zs;
                zjs++;
                zzl += (decimal)Reader["重量"];
                zcd += (decimal)Reader["长度"];
                for (i = 0; i < ks; i++)
                {
                    if ((int)Reader["捆号"] == khs[i])
                    {
                        if (!Convert.IsDBNull(Reader["原料供货"]))
                        {
                            ghs[i] = (string)Reader["原料供货"];
                        }
                        lhs[i] = (string)Reader["炉号"];
                        zls[i] = ((decimal)Reader["重量"]).ToString();
                        cds[i] = ((decimal)Reader["长度"]).ToString();
                        if ((this.ChanPinID.Text == "1" || this.ChanPinID.Text == "3") && zs != 19)
                        {
                            ts = "000000000" + khs[i];
                            ts=ts.Substring(ts.Length-9);
                            beizhu += " " + ts.Substring(0, 4) + "-" + ts.Substring(5) + "为" + zs + "支";
                        }
                        else if ((this.ChanPinID.Text == "2" || this.ChanPinID.Text == "4") && zs != 7)
                        {
                            ts = "000000000" + khs[i];
                            ts = ts.Substring(ts.Length - 9);
                            beizhu += " " + ts.Substring(0, 4) + "-" + ts.Substring(5) + "为" + zs + "支";
                        }

                    }
                }
            }

            Reader.Close();
            Conn.Close();
            Reader.Dispose();
            Cmd.Dispose();
            Conn.Dispose();

            if (ks != zjs)
            {
                this.Notice = "·部分捆号有误，请检查后重新输入";
            }
            else
            {
                kidlist = kidlist.Substring(1);
                this.Notice = "·数据校验通过";
            }
            this.ZZL.Text = zzl.ToString();
            this.ZCD.Text = zcd.ToString();
            this.ZZS.Text = zzs.ToString();
            this.ZJS.Text = zjs.ToString();

            this.GHList.Value = "|"+string.Join("|", ghs);
            this.LHList.Value = "|" + string.Join("|", lhs);
            this.ZLList.Value = "|" + string.Join("|", zls);
            this.CDList.Value = "|" + string.Join("|", cds);
            //this.BeiZhu.Value = beizhu;
            return beizhu;
        }
    }
}
